﻿using System;
using System.Threading;

namespace MySpace.ConfigurationSystem
{
	internal class HandleWithCount
	{
		private readonly AutoResetEvent _handle;
		private int _count;
		private int _accumulator;
		internal int AccumulatorValue
		{
			get { return _accumulator; }
		}

		internal HandleWithCount(AutoResetEvent handle, int initialCount)
		{
			if (handle == null)
			{
				throw new ArgumentNullException("handle");
			}

			_handle = handle;
			_count = initialCount;

		}

		internal void Decrement(int resultCount)
		{
			Interlocked.Add(ref _accumulator, resultCount);
			if (Interlocked.Decrement(ref _count) == 0)
			{
				_handle.Set();
			}			
		}
		
		internal void Decrement()
		{
			if (Interlocked.Decrement(ref _count) == 0)
			{
				_handle.Set();
			}			
		}
	}
}
